package com.sc.byahi.user.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sc.byahi.user.shared.constants.Lists;

public class ConstantsManager {
	private Logger logger = Logger.getLogger("com.sc.byahi.user.server.ConstantsManager");
	private static ConstantsManager singleton = null;

	/**
	 * Degrees - Bachelors(Engg) [BArch BCA Masters(Engg) MArch MCA]
	 */
	private final Map<Lists, Map<String, List<String>>> lists = new HashMap<Lists, Map<String, List<String>>>();

	private final Properties countryCodes = new Properties();
	
	public Map<Lists, Map<String, List<String>>> getLists() {
		return lists;
	}

	public Properties getCountryCodeList() {
		return countryCodes;
	}

	private ConstantsManager() {
		for (Lists type : Lists.values()) {
			Map<String, List<String>> map = new HashMap<String, List<String>>();
			lists.put(type, map);
			logger.log(Level.INFO, type.getFileName());
			InputStream is = this.getClass().getResourceAsStream(type.getFileName());
			LineNumberReader reader = new LineNumberReader(new InputStreamReader(is));
			String currLine = null;
			String currGroup = null;
			List<String> currList = null;
			try {
				while ((currLine = reader.readLine()) != null) {
					currLine.trim();
					if (currLine.startsWith("#")) {// group changed
						if (currLine.length() == 1) {
							currGroup = "";
						} else {
							currGroup = currLine.substring(1);
						}
						if (map.containsKey(currGroup)) {
							currList = map.get(currGroup);
						} else {
							currList = new ArrayList<String>();
							map.put(currGroup, currList);
						}
						continue;// to value
					} else if ("".equals(currLine)) {
						continue;
					} else {
						currList.add(currLine);
					}
				}
			} catch (IOException e) {
				logger.log(Level.SEVERE, "Error while loading lists.", e);
			}
		}
		// Now load country key value mapped list
		try {
			InputStream is = this.getClass().getResourceAsStream("country-code");

			countryCodes.load(is);
			lists.get(Lists.COUNTRIES).get("").clear();
			lists.get(Lists.COUNTRIES).get("").addAll(countryCodes.stringPropertyNames());
			countryCodes.values();
			
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Error while loading country list.", e);
		}
		

		
	}

	public static ConstantsManager getInstance() {
		if (singleton == null) {
			singleton = new ConstantsManager();
		}
		return singleton;
	}

	public Map<String, List<String>> getList(Lists type) {
		return lists.get(type);
	}
}
